const path = require('path')
const fs = require('fs')
const webpack = require('webpack')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')

const base = path.resolve(__dirname, '../')
const src = path.resolve(__dirname, '../src')
const dist = path.resolve(__dirname, '../dist')
const buildPath = 'build/'
const publicPath = '/assets/'

class FileTask {
  constructor(file) {
    this.src = `${src}/${file}`
    this.dist = `${dist}/${file}`
  }

  copy() {
    fs.readFile(this.src, (err, buf) => {
      if (err) { return }
      fs.writeFile(this.dist, buf, err => err && console.log('write:', err))
    })
  }
}

const files = [
  new FileTask('favicon.ico'),
  new FileTask('sw.js'),
  new FileTask('manifest.json'),
  new FileTask('icon-manifest.jpg'),
]
files.map(file => {
  file.copy()
  fs.watch(file.src, () => {
    console.log('re copy')
    files.map(file => file.copy())
  })
})
console.log('watching single files ...')

module.exports = {  
  mode: 'development',

  entry: {
    app: `${src}/index.js`,
    vendor:[
      'react',
      'react-dom',
      'axios',
    ],
  },

  output: {
    path: dist,
    publicPath: publicPath,
    filename: `${buildPath}/[name].[hash:8].js`
  },

  optimization: {
    splitChunks: {
      chunks: 'all',
      name: 'vendor'
    }
  },

  module: {
    rules: [
      {
        test: /\.js$/, exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            "presets": ["env", "react"],
          }
        }
      },
      {
        test: /\.less$/,
        use: [ 
          MiniCssExtractPlugin.loader,
          'css-loader', 
          'less-loader' 
        ]
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          { 
            loader: 'file-loader',
            options: {
              name: `${buildPath}/[name]-[hash:8].[ext]`,
            }
          }
        ]
      }
    ]
  },

  plugins: [
    new CleanWebpackPlugin(['*'], { root:dist }),

    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: `${buildPath}/[name].[hash:8].css`,
      chunkFilename: `${buildPath}/[id].[hash:8].css`
    }),

    new HtmlWebpackPlugin({ 
      template: `${src}/index.html`,
    }),

    new webpack.HotModuleReplacementPlugin(),
  ]

}